﻿namespace NKernel.Core.Impl
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Xml;

    using log4net;

    internal class ConfigLoader
    {
        #region Fields

        private const string AppSettingsXpath = "/configuration/appSettings";
        private const string ConfigFile = "Kernel.config";

        private static readonly ILog Logger = LogManager.GetLogger(typeof(ConfigLoader));

        #endregion Fields

        #region Methods

        public IDictionary<string, string> LoadConfigFile()
        {
            var configuration = new Dictionary<string, string>();
            if (Logger.IsDebugEnabled)
            {
                Logger.DebugFormat("Attempting to load the kernel config file - {0}", ConfigFile);
            }
            var fileInfo = new FileInfo(ConfigFile);
            if (fileInfo.Exists)
            {
                Stream resourceStream = new FileStream(fileInfo.FullName, FileMode.Open);
                var xmlDoc = new XmlDocument();
                try
                {
                    xmlDoc.Load(resourceStream);
                }
                catch (Exception exception)
                {
                    Logger.Error(string.Format("Problem loading the XML descriptor from file: {0}",
                        fileInfo), exception);
                    return configuration;
                }

                XmlNodeList nodes = xmlDoc.SelectNodes(AppSettingsXpath);

                if (nodes == null)
                {
                    Logger.Warn("Why no configuration settings for " + fileInfo);
                    return configuration;
                }

                foreach (XmlNode node in nodes)
                {
                    XmlNodeList nodeAddList = node.SelectNodes("add");
                    foreach (XmlNode nodeAdd in nodeAddList)
                    {
                        if (nodeAdd == null)
                        {
                            continue;
                        }
                        string key = nodeAdd.Attributes["key"].InnerText;
                        string value = nodeAdd.Attributes["value"].InnerText;

                        if (Logger.IsDebugEnabled)
                        {
                            Logger.DebugFormat("Found configuration: {0} = {1}", key, value);
                        }

                        configuration.Add(key, value);
                    }
                }
            }
            else
            {
                Logger.WarnFormat("Unable to find the kernel config file in the same directory: {0}", ConfigFile);
            }

            return configuration;
        }

        #endregion Methods
    }
}